<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="86px">
      <el-form-item label="医生名" prop="doctorId">
        <el-select v-model="queryParams.doctorId" placeholder="请选择医生" clearable>
          <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联话题" prop="topicId">
        <el-select v-model="queryParams.topicId" placeholder="请选择话题" clearable>
          <el-option v-for="item in topicList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['video:video:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['video:video:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['video:video:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['video:video:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="视频ID" align="center" prop="id" />
      <el-table-column label="视频标题" align="center" prop="title" />
      <!-- 文章内容列修改：先去除HTML标签，再处理溢出 -->
      <el-table-column label="视频内容" align="center">
        <template slot-scope="scope">
          <div class="video-content-text">
            {{ stripHtmlTags(scope.row.content) }}
          </div>
        </template>
      </el-table-column>
      <!-- 表格中显示视频预览 -->
      <el-table-column label="视频链接" align="center">
        <template slot-scope="scope">
          <video v-if="scope.row.videoUrl" :src="scope.row.videoUrl" controls
            style="max-width: 210px; max-height: 150px;"></video>
          <span v-else>无视频</span>
        </template>
      </el-table-column>
      <!-- 发布医生（显示姓名） -->
      <el-table-column label="发布医生" align="center">
        <template slot-scope="scope">
          <!-- 空值保护：避免对象为null时报错 -->
          {{ scope.row.doctor && scope.row.doctor.name }}
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="阅读量" align="center" prop="readCount" />
      <el-table-column label="收藏量" align="center" prop="collectCount" />
      <el-table-column label="点赞量" align="center" prop="approve" />
      <!-- 关联话题（显示名称） -->
      <el-table-column label="关联话题" align="center">
        <template slot-scope="scope">
          {{ scope.row.topic && scope.row.topic.name }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['video:video:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['video:video:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改视频管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="92px">
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <!-- 视频上传组件 -->
        <el-form-item label="视频链接" prop="videoUrl">
          <el-upload class="video-uploader" :action="uploadUrl" :headers="uploadHeaders"
            :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
            :file-list="fileList" accept="video/*" list-type="text">
            <i v-if="!form.videoUrl" class="el-icon-plus video-uploader-icon"></i>
            <video v-else :src="form.videoUrl" controls style="max-width: 400px;"></video>
          </el-upload>
          <div style="margin-top: 10px; font-size: 12px; color: #606266;">
            支持MP4、AVI格式，大小不超过100MB
          </div>
        </el-form-item>
        <!-- 发布医生：编辑显名称，新增输 ID -->
        <el-form-item label="医生名" prop="doctorId">
          <el-select v-model="form.doctorId" placeholder="请选择医生" clearable>
            <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="time">
          <el-date-picker clearable v-model="form.time" type="date" value-format="yyyy-MM-dd" placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="关联话题" prop="topicId">
          <el-select v-model="form.topicId" placeholder="请选择话题" clearable>
            <el-option v-for="item in topicList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listVideo,
    getVideo,
    delVideo,
    addVideo,
    updateVideo,
    listDoctor,
    listTopic
  } from "@/api/knowledge/video"
  import {
    getToken
  } from "@/utils/auth" // 导入RuoYi的Token工具

  export default {
    name: "Video",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 视频管理表格数据
        videoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 上传相关配置
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // RuoYi默认上传接口
        uploadHeaders: {
          Authorization: "Bearer " + getToken() // 携带Token认证
        },
        fileList: [], // 上传文件列表
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          collectCount: null,
          readCount: null,
          approve: null,
          doctorId: null,
          topicId: null,
        },
        //医生列表
        doctorList: [],
        //话题列表
        topicList: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          title: [{
            required: true,
            message: "视频标题不能为空",
            trigger: "blur"
          }],
          content: [{
            required: true,
            message: "视频内容不能为空",
            trigger: "blur",
          }, ],
          doctorId: [{
            required: true,
            message: "发布医生不能为空",
            trigger: "blur"
          }],
          time: [{
            required: true,
            message: "发布时间不能为空",
            trigger: "blur"
          }],
          topicId: [{
            required: true,
            message: "关联话题不能为空",
            trigger: "blur"
          }],
          videoUrl: [ // 新增视频必填验证
            {
              required: true,
              message: "请上传视频",
              trigger: "change"
            }
          ]
        }
      }
    },
    created() {
      this.getList(),
        this.getDoctorList(),
        this.getTopicList()
    },
    methods: {
      /** 查询视频管理列表 */
      getList() {
        this.loading = true
        listVideo(this.queryParams).then(response => {
          this.videoList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      /** 查询医生列表 */
      getDoctorList() {
        listDoctor({
          pageNum: 1,
          pageSize: 9999,
        }).then((res) => {
          if (res.code === 200) {
            this.doctorList = res.rows;
          }
        });
      },
      /** 查询话题列表 */
      getTopicList() {
        listTopic().then((res) => {
          if (res.code === 200) {
            this.topicList = res.rows;
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          title: null,
          content: null,
          videoUrl: null,
          doctorId: null,
          time: null,
          readCount: null,
          collectCount: null,
          approve: null,
          topicId: null,
          del: null
        }
        this.fileList = [] // 清空上传文件列表
        this.resetForm("form")
      },
      stripHtmlTags(html) {
        if (!html) return "";
        const tempDiv = document.createElement("div");
        tempDiv.innerHTML = html;
        return tempDiv.textContent || tempDiv.innerText;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm")
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加视频管理"
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        getVideo(id).then(response => {
          this.form = response.data
          // 回显已上传的视频
          if (this.form.videoUrl) {
            this.fileList = [{
              name: 'video',
              url: this.form.videoUrl
            }]
          }
          this.open = true
          this.title = "修改视频管理"
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateVideo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addVideo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm('是否确认删除视频管理编号为"' + ids + '"的数据项？').then(function() {
          return delVideo(ids)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('video/video/export', {
          ...this.queryParams
        }, `video_${new Date().getTime()}.xlsx`)
      },
      /** 上传成功处理 */
      handleUploadSuccess(response, file, fileList) {
        if (response.code === 200) {
          this.form.videoUrl = response.url // 保存视频链接
          this.fileList = fileList
          this.$modal.msgSuccess("视频上传成功")
        } else {
          this.$modal.msgError(response.msg || "上传失败")
        }
      },
      /** 上传失败处理 */
      handleUploadError() {
        this.$modal.msgError("上传失败，请重试")
      },
      /** 上传前校验 */
      beforeUpload(file) {
        // 校验文件大小
        const isLt100M = file.size / 1024 / 1024 < 100
        if (!isLt100M) {
          this.$modal.msgError('视频大小不能超过100MB')
          return false
        }
        // 校验文件类型
        const isVideo = file.type.indexOf('video/') === 0
        if (!isVideo) {
          this.$modal.msgError('请上传视频文件')
          return false
        }
        return true
      },
    }
  }
</script>

<style scoped>
  /* 视频上传组件样式 */
  .video-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    text-align: center;
    padding: 20px 0;
  }

  .video-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }

  /* 视频内容溢出控制样式 */
  .video-content-text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;

  }
</style>
